<template>
  <div class="edit-question">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>编辑题目</h3>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
        style="margin: 0 200px"
      >
        <!-- 题目类型 -->
        <el-form-item label="题目类型" prop="typeId">
          <el-select
            v-model="formData.typeId"
            placeholder="请选择题目类型"
            @change="handleTypeChange"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 题目内容 -->
        <el-form-item label="题目内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入题目内容"
          />
        </el-form-item>

        <!-- 选项（单选题、多选题） -->
        <template v-if="[10001, 10002].includes(formData.typeId)">
          <el-form-item label="选项" prop="options">
            <div
              v-for="(option, index) in formData.options"
              :key="index"
              class="option-item"
            >
              <el-input
                v-model="option.content"
                :placeholder="`选项${option.key}`"
              >
                <template #prepend>{{ option.key }}</template>
              </el-input>
              <el-button
                type="danger"
                link
                @click="removeOption(index)"
                v-if="formData.options.length > 2"
              >
                删除
              </el-button>
            </div>
            <el-button
              type="primary"
              link
              @click="addOption"
              v-if="formData.options.length < 26"
              style="margin-bottom: 10px"
            >
              添加选项
            </el-button>
          </el-form-item>
        </template>

        <!-- 正确答案 -->
        <el-form-item label="正确答案" prop="answer">
          <!-- 单选题 -->
          <template v-if="formData.typeId === 10001">
            <el-radio-group v-model="formData.answer">
              <el-radio
                v-for="option in formData.options"
                :key="option.key"
                :value="option.key"
              >
                {{ option.key }}
              </el-radio>
            </el-radio-group>
          </template>

          <!-- 多选题 -->
          <template v-if="formData.typeId === 10002">
            <el-checkbox-group v-model="formData.answer">
              <el-checkbox
                v-for="option in formData.options"
                :key="option.key"
                :value="option.key"
              >
                {{ option.key }}
              </el-checkbox>
            </el-checkbox-group>
          </template>

          <!-- 判断题 -->
          <template v-if="formData.typeId === 10003">
            <el-radio-group v-model="formData.answer">
              <el-radio value="true">正确</el-radio>
              <el-radio value="false">错误</el-radio>
            </el-radio-group>
          </template>

          <!-- 填空题 -->
          <template v-if="formData.typeId === 10004">
            <el-input v-model="formData.answer" placeholder="请输入正确答案" />
          </template>

          <!-- 简答题 -->
          <template v-if="formData.typeId === 10005">
            <el-input
              v-model="formData.answer"
              type="textarea"
              :rows="4"
              placeholder="请输入参考答案"
            />
          </template>
        </el-form-item>

        <!-- 解析 -->
        <el-form-item label="解析" prop="analysis">
          <el-input
            v-model="formData.analysis"
            type="textarea"
            :rows="4"
            placeholder="请输入题目解析"
          />
        </el-form-item>

        <!-- 难度 -->
        <el-form-item label="难度" prop="difficulty">
          <el-rate v-model="formData.difficulty" :max="5" show-score />
        </el-form-item>

        <!-- 是否公开 -->
        <el-form-item label="是否公开" prop="isPublic">
          <el-switch
            v-model="formData.isPublic"
            active-value="true"
            inactive-value="false"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { questionApi } from "../../api/questionApi";
import { typeOptions } from "../../utils/utils";

const router = useRouter();
const route = useRoute();
const formRef = ref(null);
const loading = ref(false);

// 表单数据
const formData = reactive({
  typeId: "",
  content: "",
  options: [
    { key: "A", content: "" },
    { key: "B", content: "" },
    { key: "C", content: "" },
    { key: "D", content: "" },
  ],
  answer: "",
  analysis: "",
  difficulty: 3,
  isPublic: false, // 新增字段，默认不公开
});

// 表单验证规则
const rules = {
  typeId: [{ required: true, message: "请选择题目类型", trigger: "change" }],
  content: [{ required: true, message: "请输入题目内容", trigger: "blur" }],
  answer: [{ required: true, message: "请设置正确答案", trigger: "change" }],
  difficulty: [{ required: true, message: "请设置难度", trigger: "change" }],
};

// 获取题目详情
const getQuestionDetail = async () => {
  loading.value = true;
  try {
    const res = await questionApi.getQuestionDetail(route.params.id);
    const data = res.result;
    // 更新表单数据
    Object.assign(formData, {
      typeId: data.typeId,
      content: data.content,
      analysis: data.analysis,
      difficulty: data.difficulty,
      isPublic: data.isPublic ? "true" : "false",
    });
    if (data.typeId === 10002) {
      Object.assign(formData, {
        answer: JSON.parse(data.answer),
      });
    } else if (data.typeId !== 10002) {
      Object.assign(formData, {
        answer: data.answer,
      });
    }
    // 处理选项数据
    if (data.options) {
      formData.options = Object.entries(JSON.parse(data.options)).map(
        ([key, content]) => ({
          key,
          content,
        })
      );
    }
  } catch (error) {
    console.error("获取题目详情失败:", error);
    ElMessage.error("获取题目详情失败");
    router.push("/question");
  } finally {
    loading.value = false;
  }
};

// 处理题目类型变化
const handleTypeChange = (typeId) => {
  if (typeId === 10002) {
    formData.answer = []; // 多选题使用数组
  }
};

const keys = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
];

// 添加选项
const addOption = () => {
  let index = -1;
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    const isUsed = formData.options.some((option) => option.key === key);
    if (!isUsed) {
      index = i;
      break;
    }
  }
  if (index !== -1) {
    formData.options.push({ key: keys[index], content: "" });
  }
};

// 删除选项
const removeOption = (index) => {
  formData.options.splice(index, 1);
  for (let i = index; i < formData.options.length; i++) {
    formData.options[i].key = keys[i];
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理选项数据
        const options = formData.options.reduce((acc, curr) => {
          acc[curr.key] = curr.content;
          return acc;
        }, {});
        formData.answer =
          10002 === formData.typeId
            ? JSON.stringify(formData.answer)
            : formData.answer;
        const data = {
          ...formData,
          options: [10001, 10002].includes(formData.typeId)
            ? JSON.stringify(options)
            : null,
          questionId: route.params.id,
        };
        await questionApi.updateQuestion(data);
        ElMessage.success("更新成功");
        router.push("/question");
      } catch (error) {
        console.error("更新题目失败:", error);
      }
    }
  });
};

// 取消
const handleCancel = () => {
  router.back();
};

onMounted(() => {
  getQuestionDetail();
});
</script>

<style scoped>
.edit-question {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

:deep(.el-rate) {
  margin-top: 8px;
}
</style>
